package com.pb.infra.oth.util;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * 序列化工具类
 *
 * @author 金洋
 * @date 2018年1月18日
 */
@Slf4j
public class SerializeUtil {
    private SerializeUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * MD5加密方法
     *
     * @param s 加密对象字符串
     * @return 加密结果MD5字符串
     */
    public static String md5(String s) {
        String md5str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] b = md.digest(s.getBytes());
            md5str = bytesToHex(b);
        } catch (NoSuchAlgorithmException e) {
            log.error("执行失败", e);
        }
        return md5str;
    }

    /**
     * 字节转十六进制
     *
     * @param b 字节数组
     * @return String 十六进制结果字符串
     */
    public static String bytesToHex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        int digital;
        for (int i = 0; i < b.length; i++) {
            digital = b[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(digital));
        }
        return sb.toString().toUpperCase(Locale.ENGLISH);
    }

    /**
     * MD5加密
     *
     * @param str
     * @return
     */
    public static String generateMD5(String str) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }
}
